package test.administrator.example.com.mvptest1.demo.lce;

import android.os.AsyncTask;

import java.util.Collections;
import java.util.List;

public class CountriesAsyncLoader extends AsyncTask<Void, Void, List<Country>> {

	public interface CountriesLoaderListener {
		void onSuccess(List<Country> countries);

		void onError(Exception e);
	}

	private boolean shouldFail;
	private CountriesLoaderListener listener;

	public CountriesAsyncLoader(boolean shouldFail, CountriesLoaderListener listener) {
		this.listener = listener;
		this.shouldFail = shouldFail;
	}

	@Override
	protected List<Country> doInBackground(Void... params) {
		//可以替换为网络请求

		try {
			Thread.sleep(6000);
		} catch (InterruptedException e) {
			return null;
		}

		List<Country> countries = CountryApi.getCountries();
		Collections.shuffle(countries);

		return countries;
	}

	@Override
	protected void onPostExecute(List<Country> countries) {

		if (isCancelled() || countries == null) {
			return;
		}

		if (shouldFail) {
			listener.onError(new Exception("Oops something went wrong"));
		} else {
			listener.onSuccess(countries);
		}
	}

}
